package com.liuning.syn;

/**
 * 不安全的买票
 * 线程不安全，有负数
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"我").start();
        new Thread(buyTicket,"你").start();
        new Thread(buyTicket,"黄牛").start();
    }

}

class BuyTicket implements Runnable {

    //票的总数
    private int ticketNums = 10;

    //线程停止标志位
    private boolean flag = true;

    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    //判断是否有票
    public synchronized void buy() throws InterruptedException {
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        //模拟延时
        // Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums--);
    }

}
